# -*- coding: utf-8 -*-
# @author: HRUN
from pathlib import Path

from cryptography.fernet import Fernet
BASE_DIR = Path(__file__).resolve().parent


# 生成密钥并保存到文件
def generate_and_save_key():
    key = Fernet.generate_key()
    with open('secret.key', 'wb') as key_file:
        key_file.write(key)

# 从文件加载密钥
def load_key():
    with open((BASE_DIR / 'secret.key'), 'rb') as key_file:
        return key_file.read()

# 加密数据
def encrypt_field(value, key):
    cipher_suite = Fernet(key)
    encrypted_value = cipher_suite.encrypt(value.encode())
    return encrypted_value.decode()

# 解密数据
def decrypt_field(encrypted_value, key):
    cipher_suite = Fernet(key)
    decrypted_value = cipher_suite.decrypt(encrypted_value.encode())
    return decrypted_value.decode()


# 示例使用
if __name__ == "__main__":
    # 生成密钥（仅需生成一次，之后请注释掉这一行）
    # generate_and_save_key()

    # 从文件中加载密钥
    key = load_key()

    # 示例数据
    plain_text = 'gAAAAABmtdzntgt_19EDc8NWkyMHSlnANctyqMWMOgRP-ejE2E-6xBYcpmLMALwEVVcmR5mCy1uYxbxa_WeBOfo_Q1-6wzEGZQ=='

    # 加密数据
    # encrypted = encrypt_field(plain_text, key)
    # print(f'加密后的数据: {encrypted}')

    # 解密数据
    decrypted = decrypt_field(plain_text, key)
    print(f'解密后的数据: {decrypted}')